package com.jz.digital.gongxu

import com.jz.digital.base.BasePresenter
import com.jz.digital.bean.BaseEntity
import com.jz.digital.bean.ServerBean
import com.jz.digital.listener.ApiCallback
import com.jz.digital.net.DataApi
import com.jz.digital.utils.AccountManagerHelper
import com.jz.digital.utils.ErrorCode
import com.jz.digital.utils.GreenDaoUtils
import com.jz.digital.utils.GsonUtil
import com.jz.digital.utils.LogUtils
import java.util.concurrent.CountDownLatch

/**
 * @author jiangdz
 * @date 2024/11/19
 * @time 19:26
 * 用途:工序汇报
 */
class GongXuCommitPresenter : BasePresenter<IGongXuCommitView>() {
    private val tag = "GongXuCommitPresenter"
    val mGongYiList = mutableListOf<ServerBean.GXInfo>()
    val mJiTaiList = mutableListOf<ServerBean.GXInfo>()
    val mGongXuList = mutableListOf<ServerBean.GXInfo>()
    val mBanZuList = mutableListOf<ServerBean.GXInfo>()
    val mBuLiangList = mutableListOf<ServerBean.GXInfo>()
    private val mCountDown = CountDownLatch(1)

    fun initData() {
        view?.showLoading()
        getGongXuFromServer()
    }

    /**
     * 清空机台、工艺、班组数据
     */
    fun clearData() {
        mGongYiList.clear()
        mBanZuList.clear()
        mJiTaiList.clear()
    }

    private fun getGongXuFromServer() {
        LogUtils.d(tag, "工序-开始从服务器获取工序列表")
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "GX"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "工序列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mGongXuList.addAll(response.data!!)
                    }
                    view?.dismissLoading()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    view?.dismissLoading()
                }

            })
    }

    fun getBanZuFromServer(gx: String) {
        LogUtils.d(tag, "班组-开始从服务器获取工艺列表")
        if (mBanZuList.isNotEmpty()) {
            view.onBanZuSuccess()
            return
        }
        view.showLoading()
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "BZ", gx = gx))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "班组列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mBanZuList.addAll(response.data!!)
                        view.onBanZuSuccess()
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }

            })
    }

    fun getGongYiFromServer(gx: String) {
        LogUtils.d(tag, "工艺-开始从服务器获取工艺列表")
        if (mGongYiList.isNotEmpty()) {
            view.onGongYiSuccess()
            return
        }
        view.showLoading()
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "GY", gx = gx))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "工序-工艺列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mGongYiList.addAll(response.data!!)
                        view.onGongYiSuccess()
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序-工艺列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }

            })
    }

    fun getJiTaiFromServer(gx: String) {
        LogUtils.d(tag, "机台-开始从服务器获取机台列表")
        if (mJiTaiList.isNotEmpty()) {
            view.onJiTaiSuccess()
            return
        }
        view.showLoading()
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "JT", gx = gx))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "机台-机台列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mJiTaiList.addAll(response.data!!)
                        view.onJiTaiSuccess()
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序-机台列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }

            })
    }

    fun getBuLiangFromServer() {
        LogUtils.d(tag, "不良-开始从服务器获取不良列表")
        if (mBuLiangList.isNotEmpty()) {
            view.onBuLiangSuccess()
            return
        }
        view.showLoading()
        DataApi.api.getGXInfo(ServerBean.GXInfoRequest(mode = 2, type = "BL"))
            .enqueue(object : ApiCallback<BaseEntity<List<ServerBean.GXInfo>?>>() {
                override fun onSuccess(response: BaseEntity<List<ServerBean.GXInfo>?>?) {
                    LogUtils.d(tag, "工序-不良列表获取成功 response=${GsonUtil.toJson(response)}")
                    if (response != null && !response.data.isNullOrEmpty()) {
                        mBuLiangList.addAll(response.data!!)
                        view.onBuLiangSuccess()
                    }
                    typeLoadFinish()
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(
                        tag,
                        "工序-不良列表获取失败 error=${t?.message},code=$code,message=$message"
                    )
                    typeLoadFinish()
                }
            })
    }

    fun commit(
        barcode: String,
        pda: String,
        no1: String,
        no9: String,
        no6: String,
        no7: String,
        no8: String,
        no10: String,
        qty3: Int,
        qty4: Int,
        exit: Boolean
    ) {
        val userInfo = GreenDaoUtils.getUserInfo(AccountManagerHelper.getInstance().userId)
        if (userInfo == null) {
            LogUtils.d(tag, "用户信息为空")
            return
        }
        view?.showLoading()
        val request = ServerBean.GXReportRequest(
            mode = 6, barcode = barcode, wk_id = userInfo.userId, wk_name = userInfo.userName,
            pda = pda, no1 = no1, no9 = no9, no6, no7, no8, no10, qty3, qty4
        )
        LogUtils.d(tag, "工序汇报 request=${GsonUtil.toJson(request)}")
        DataApi.api.gongXuReport(request)
            .enqueue(object : ApiCallback<BaseEntity<ServerBean.GXReportResponse?>>() {
                override fun onSuccess(response: BaseEntity<ServerBean.GXReportResponse?>?) {
                    LogUtils.d(tag, "工序汇报成功 response=${GsonUtil.toJson(response)}")
                    view?.dismissLoading()
                    if (response != null) {
                        if (response.code == ErrorCode.CODE_NOT_ALLOW_SIMULTANEOUS_RECEIPT) {
                            view?.reportFailed(response.message ?: "")
                            return
                        }
                        if (response.data != null) {
                            view?.reportSuccess(response.data!!)
                        }
                        if (exit) {
                            view?.actionSuccess()
                        }
                    }
                }

                override fun onError(t: Throwable?, code: Int, message: String?) {
                    LogUtils.d(tag, "工序汇报异常 error=${t?.message},code=$code,message=$message")
                    if (isAttachView) {
                        view?.dismissLoading()
                        if (exit) {
                            view?.actionFail(message)
                        } else {
                            view?.reportFailed(message)
                        }
                    }


                }
            })
    }

    fun getGongXuTitle(basId: String): String {
        val result = mGongXuList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    fun getJiTaiTitle(basId: String): String {
        val result = mJiTaiList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    fun getGongYiTitle(basId: String): String {
        val result = mGongYiList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    fun getBanZuTitle(basId: String): String {
        val result = mBanZuList.firstOrNull { it.basId == basId }
        return if (result != null && !result.basName.isNullOrEmpty()) result.basName
            ?: basId else basId
    }

    private fun typeLoadFinish() {
        mCountDown.countDown()
        if (mCountDown.count == 0L) {
            view?.dismissLoading()
        }
    }
}